/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ilookinto.jr;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Scanner;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.log4j.Logger;
import org.ilookinto.doexe.Processor;

/**
 *
 * @author Administrator
 */
public class LocalProxyServlet extends HttpServlet {

    Processor.Pair<PrintWriter, Scanner, Scanner> pair;
    Repository rep;
    static Session jcrSession;
    Logger log = Logger.getLogger(LocalProxyServlet.class);

    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        String nodeName = request.getParameter("node");
        String outType = request.getParameter("outType");
        try {
            nodeName = URLDecoder.decode(nodeName, "UTF-8");
        } catch (Exception e) {
        }
        String fileName = nodeName;
        //String localAddress= request.getLocalAddr();
        int localPort = request.getLocalPort();
        //int fileNamePartIndex = fileName.lastIndexOf("/");
        //String fileNamePart = fileName.substring(fileNamePartIndex + 1);
        //fileNamePart = URLEncoder.encode(fileNamePart, "UTF-8");
        fileName = fileName.trim();
        fileName = URLEncoder.encode(fileName, "UTF-8");
        fileName = fileName.replaceAll("%2F", "/");
        fileName = fileName.replaceAll("\\+", "%20");
        String urls = "http://localhost:" + localPort + "/ilookinto/repository/default/" + fileName;


        log.info("url=" + urls);

        if (!URLUtils.exists(urls)) {
            log.info("not found?" + urls);
            response.setStatus(HttpStatus.SC_NOT_FOUND);
            return;

        }
        try {
            URL url = new URL(urls);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestProperty("Authorization", "Basic " + URLUtils.auth);
            InputStream is = urlConnection.getInputStream();
            if ("text".equalsIgnoreCase(outType)) {
                MyTikaCLI.main2(new String[]{});
            } else {
                String mimeType = URLConnection.guessContentTypeFromName(fileName);
                if (mimeType == null) {
                    if (fileName.endsWith(".doc")) {
                        mimeType = "application/msword";
                    } else if (fileName.endsWith(".xls")) {
                        mimeType = "application/vnd.ms-excel";
                    } else if (fileName.endsWith(".ppt")) {
                        mimeType = "application/mspowerpoint";
                    } else {
                        mimeType = "application/octet-stream";
                    }
                }
                response.setContentType(mimeType);
                BufferedInputStream bir = new BufferedInputStream(is);
                OutputStream os = response.getOutputStream();
                byte[] b = new byte[10 * 1024];
                int n;
                while ((n = bir.read(b)) > 0) {
                    os.write(b, 0, n);
                }

                os.close();
            }
        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_NOT_FOUND, e.getMessage());
            log.error("error", e);
        }
    }
}
